package com.vcit.system.util;

import com.deepoove.poi.*;
import org.apache.poi.xwpf.usermodel.*;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class WordTemplateUtil {

    /**
     * 用Map中的内容替换Word模板中的${key}占位符
     */
    public static byte[] replaceAndGenerate(String templatePath, Map<String, String> params) throws IOException {
        try (InputStream is = WordTemplateUtil.class.getClassLoader().getResourceAsStream(templatePath);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            // 配置poi-tl
          /*  Configure config = Configure.builder()
                    .bind("studentName", new TextRenderPolicy())
                    .bind("majorName", new TextRenderPolicy())
                    .bind("clazzName", new TextRenderPolicy())
                    .bind("deptName", new TextRenderPolicy())
                    .bind("zsYear", new TextRenderPolicy())
                    .build();

            XWPFTemplate template = XWPFTemplate.compile(is, config).render(params);*/
            XWPFTemplate template = XWPFTemplate.compile(is).render(params);
            template.write(baos);
            return baos.toByteArray();
        }
    }
   /* public static byte[] replaceAndGenerate(String templatePath, Map<String, String> params) throws IOException {
        try (InputStream is = WordTemplateUtil.class.getClassLoader().getResourceAsStream(templatePath);
             XWPFDocument doc = new XWPFDocument(is);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            // 替换段落中的占位符
            for (XWPFParagraph para : doc.getParagraphs()) {
                replaceInParagraph(para, params);
            }
            // 替换表格中的占位符
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph para : cell.getParagraphs()) {
                            replaceInParagraph(para, params);
                        }
                    }
                }
            }
            doc.write(baos);
            return baos.toByteArray();
        }
    }

    private static void replaceInParagraph(XWPFParagraph para, Map<String, String> params) {
        for (XWPFRun run : para.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    text = text.replace("${" + entry.getKey() + "}", entry.getValue());
                }
                run.setText(text, 0);
            }
        }
    }*/
}
